package service

import (
	"app/model"
	"app/pkg/e"
	"app/pkg/jwt"
	"app/serializer"
)

// 用户注册服务
type UserService struct {
	Username string `form:"username" json:"username" binding:"required,min=3,max=15" example:"lijia"`
	Password string `form:"password" json:"password" binding:"required,min=5,max=16" example:"abcd0000"`
}

func (service *UserService) Register() serializer.Response {
	var user model.User
	var count int64
	model.DB.Model(&model.User{}).Where("username=?", service.Username).First(&user).Count(&count)
	if count == 1 {
		return serializer.MsgResponse(e.ErrorExistUser)
	}
	user.Username = service.Username
	// 加密密码
	if err := user.SetPassword(service.Password); err != nil {
		return serializer.MsgResponse(e.ErrorEncryptPwd)
	}
	// 创建用户
	if err := model.DB.Create(&user).Error; err != nil {
		return serializer.MsgResponse(e.ErrorDatabase)
	}
	return serializer.MsgResponse(e.SUCCESS)
}

// 用户登陆函数
func (service *UserService) Login() serializer.Response {
	var user model.User
	var count int64
	model.DB.Model(&model.User{}).Where("username=?", service.Username).First(&user).Count(&count)
	if count == 0 {
		return serializer.MsgResponse(e.ErrorNotExistUser)
	}
	if !user.CheckPassword(service.Password) {
		return serializer.MsgResponse(e.ErrorInvalidPwd)
	}
	token, err := jwt.GenerateToken(user.ID)
	if err != nil {
		return serializer.MsgResponse(e.ErrorTokenGenerate)
	}
	if err := model.DB.Model(&user).Update("Token", token).Error; err != nil {
		return serializer.MsgResponse(e.ErrorTokenGenerate)
	}
	return serializer.Response{
		Code: e.SUCCESS,
		Data: serializer.BuildUser(user),
		Msg:  e.GetMsg(e.SUCCESS),
	}
}
